var fs = require('fs');
var path = require('path');
var _ = require('underscore');
var crypto = require('crypto');
var session = require('express-session');
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false })

module.exports = function (app) {
  app.get('/', function (req, res) {
    res.render('index', { ip: req.ip });
  });
  app.post('/login', urlencodedParser, function (req, res) {
    var account = req.body.account;
    var password = req.body.password;
    var users = [];
    var usersPath = path.normalize(path.resolve('data') + '/users.json');
    if (fs.existsSync(usersPath)) {
      users = JSON.parse(fs.readFileSync(usersPath, 'utf-8'));
    } else {
      users = [{ "account": "admin", "password": "123", "admin": true,"projects":[] }];
    }
    var user = _.filter(users, function (p) { return p.account == account });
    if (user.length < 1) {
      res.json({ success: false, message: '帐号或者密码不正确' });
    }
    if (user[0].password.length == 32) {
      if (crypto.createHash('md5').update(password + 'webdeploy$#@!').digest('hex') == user[0].password) {
        req.session.sign = true;
        req.session.account = user[0].account;
        req.session.admin = user[0].admin;
        req.session.projects = user[0].projects;
        res.json({ success: true, data: '/main' });
      } else {
        res.json({ success: false, message: '帐号或者密码不正确' });
      }
    } else {
      if (password == user[0].password) {
        req.session.sign = true;
        req.session.account = user[0].account;
        req.session.admin = user[0].admin;
        req.session.projects = user[0].projects;
        _.each(users, function (p) {
          if (p.account == user[0].account) {
            p.password = crypto.createHash('md5').update(p.password + 'webdeploy$#@!').digest('hex');
          }
        });
        fs.writeFile(usersPath, JSON.stringify(users), function (err) {
          if (err) throw err;
          console.log('写入完成');
        })
        res.json({ success: true, data: '/main' });
      } else {
        res.json({ success: false, message: '帐号或者密码不正确' });
      }
    }
  });
  app.get('/main', function (req, res) {
    res.render('main');
  });
  app.get('/admin/users',function(req,res){
    res.render('admin/users');
  });
};
